﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace X23.Util.StringUtil
{
    public static class StringUtil
    {
        /// <summary>
        /// 将大驼峰命名转为小驼峰命名
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string RenameCamelCase(this string str)
        {
            var firstChar = str[0];
            if (firstChar == char.ToLowerInvariant(firstChar))
            {
                return str;
            }
            var name = str.ToCharArray();
            name[0] = char.ToLowerInvariant(firstChar);
            return new String(name);
        }
        /// <summary>
        /// 将大驼峰命名转为蛇形命名
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string RenameSnakeCase(this string str)
        {
            var builder = new StringBuilder();
            var name = str;
            var previousUpper = false;
            for (var i = 0; i < name.Length; i++)
            {
                var c = name[i];
                if (char.IsUpper(c))
                {
                    if (i > 0 && !previousUpper)
                    {
                        builder.Append('_');
                    }
                    builder.Append(char.ToLowerInvariant(c));
                    previousUpper = true;
                }
                else
                {
                    builder.Append(c);
                    previousUpper = false;
                }
            }
            return builder.ToString();
        }
    }
}
